package com.study.shengsiyuan.example09;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

public class _3_NioServer2 {
	private static Map<String,SocketChannel>  clientMap =new HashMap<>();

	public static void main(String[] args) throws IOException {
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.configureBlocking(false);
		ssc.bind(new InetSocketAddress(8899));
		Selector s = Selector.open();
		ssc.register(s, SelectionKey.OP_ACCEPT);
		while(s.select()>0) {
			Set<SelectionKey> sks =s.selectedKeys();

			for (SelectionKey sk: sks) {
				ByteBuffer bb = ByteBuffer.allocate(1024);
				if(sk.isAcceptable()) {
					System.out.println("---Acceptable  SelectionKe----- ： "+sks);

					ServerSocketChannel ssc2 =(ServerSocketChannel)sk.channel();
					SocketChannel sc = ssc2.accept();
					sc.configureBlocking(false);
					sc.register(s, SelectionKey.OP_READ);
					String key ="【"+UUID.randomUUID()+"】";
					clientMap.put(key, sc);
				}else if(sk.isReadable()) {
					System.out.println("---Readable  SelectionKe----- ： "+sks);
					SocketChannel sc =(SocketChannel)sk.channel();
					 int count = sc.read(bb);
					 bb.flip();
					 if(count>0) {
						 Charset ch =Charset.forName("UTF-8");
						 String msg = String.valueOf(ch.decode(bb).array());
						 System.out.println(sc.getLocalAddress() + " 客户端发送的信息 ： " + msg);

						 for (Entry<String, SocketChannel>  socketChannel: clientMap.entrySet()) {
							bb.clear();
							if(socketChannel.equals(sc)) {
								bb.put(("自己发送的消息  :  "+ msg).getBytes());
							}else {
								bb.put((socketChannel.getKey() +"客户端发送的消息  :  "+ msg).getBytes());
							}
							bb.flip();
							socketChannel.getValue().write(bb);
						 }
					 }
				}
				sks.remove(sk);
			}
		}

	}
}
